import { watch, computed, toRaw } from 'vue';
import showCfg from '../flowable/showConfig';

export default function (modeler, element, formData) {
  const elementType = computed(() => {
    const bizObj = element.businessObject;
    return bizObj.eventDefinitions ? bizObj.eventDefinitions[0].$type : bizObj.$type;
  });

  const showConfig = computed(() => {
    return showCfg[elementType.value] || {};
  });

  function updateProperties(properties) {
    const modeling = modeler.get('modeling');
    try {
      modeling.updateProperties(toRaw(element), properties);
    } catch (_) {
      //
    }
  }

  watch(
    () => formData.value.id,
    (val) => {
      updateProperties({ id: val });
    },
  );

  watch(
    () => formData.value.name,
    (val) => {
      updateProperties({ name: val });
    },
  );

  watch(
    () => formData.value.documentation,
    (val) => {
      if (!val) {
        updateProperties({ documentation: [] });
        return;
      }
      const documentationElement = modeler
        .get('moddle')
        .create('bpmn:Documentation', { text: val });
      updateProperties({ documentation: [documentationElement] });
    },
  );

  return {
    elementType,
    showConfig,
    updateProperties,
  };
}
